package com.kis.excel;

import com.kis.ExcelObject;
import jxl.Sheet;
import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * Created by yks on 15-11-27.
 */
public class ReadExcelCountry {
    public static Map<String, String> xls2String(File file) {
        Map<String,String> countryMap = new HashMap<String, String>();
        try {
            FileInputStream fis = new FileInputStream(file);
            Workbook rwb = Workbook.getWorkbook(fis);
            Sheet sheet1 = rwb.getSheet(0);
            String id = null;
            String countrayName = null;
            for (int i = 1; i < 271; i++) {
                id = sheet1.getRow(i)[0].getContents();
                countrayName = sheet1.getRow(i)[3].getContents();
                if (StringUtils.isNotBlank(countrayName)) {
                    countryMap.put(countrayName, id);
                }
            }
            fis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println(countryMap.size());
        return countryMap;
    }

    public static void writeExcel(List<ExcelObject> excelObjects, String path) {
        WritableWorkbook wwb = null;
        try {
            wwb = Workbook.createWorkbook(new File(path));
            WritableSheet wSheet = wwb.createSheet("sheet1", 0);
            for (int i = 0; i < excelObjects.size(); i++) {
                Label label1 = new Label(1, i, excelObjects.get(i).getHead() + excelObjects.get(i).getMethod());
                Label label2 = new Label(2, i, excelObjects.get(i).getCode());
//                Label label2 = new Label(2,i, excelObjects.get(i).getMethod());
//                Label label3 = new Label(3,i, excelObjects.get(i).getCode());
//                Label label4 = new Label(4,i, excelObjects.get(i).getHead()+excelObjects.get(i).getMethod());
                wSheet.addCell(label1);
                wSheet.addCell(label2);
//                wSheet.addCell(label3);
//                wSheet.addCell(label4);
            }
            wwb.write();
            wwb.close();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (RowsExceededException e) {
            e.printStackTrace();
        } catch (WriteException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        File file = new File("/home/yks/country.xls");
        Map<String, String> maps = xls2String(file);
//        writeExcel(excelObjects, "/home/yks/w.xls");
    }
}

